package com.baiyang.server.control.article;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.baiyang.server.model.article.ArticleState;
import com.baiyang.server.model.article.ArticleTypeRel;
import com.baiyang.server.model.base.ArticleType;
import com.baiyang.server.model.base.Notice;
import com.baiyang.server.service.article.ArticleStateService;
import com.baiyang.server.service.article.ArticleTypeRelService;
import com.baiyang.server.service.base.ArticleTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import com.baiyang.server.annotation.Jurisdiction;
import com.baiyang.server.model.article.Article;
import com.baiyang.server.model.PageEntity;
import com.baiyang.server.service.article.ArticleService;
import com.baiyang.server.tools.Letter;
import com.baiyang.server.tools.DataTool;
import com.baiyang.server.tools.SubjectNotNull;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/articleOperation")
@Jurisdiction(value = "/articleOperation")
public class ArticleCon {
	@Autowired
	private ArticleService articleService = null;
	@Autowired
	private ArticleTypeRelService articleTypeRelService;
	@Autowired
	private ArticleTypeService articleTypeService;
	@Autowired
	private ArticleStateService articleStateService;
	/**
	 * 根绝条件分页获取数据
	 * @return
	 */
	@Jurisdiction(value = "getPage")
	@RequestMapping(value = "/getPage",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<Article> getPage(@RequestBody JSONObject object){
		Letter<Article> letter = new Letter<Article>();
		try {
			PageEntity<Article> result = articleService.getPage(object);
			result.getDatas().forEach(e->{
				ArticleTypeRel rel = new ArticleTypeRel();
				rel.setArticleId(e.getId());
				List<ArticleTypeRel> rels = articleTypeRelService.selectList(rel);
				List<String> ids = new ArrayList<>();
				rels.forEach(r->{
					ids.add(r.getTypeId());
				});
				List<ArticleType> articleTypes = articleTypeService.selectByIds(ids);
				e.setArticleTypes(articleTypes);
			});
			letter.setList(result.getDatas());
			letter.setTotal(result.getCount());
			letter.setDetail("数据获取成功");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据获取失败！");
		}
		return letter;
	}

	/**
	 * 获取作者作品当日阅读量
	 * @return
	 */
	@Jurisdiction(value = "getReadNum")
	@RequestMapping(value = "/getReadNum",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<Map<String,Object>> getReadNum(@RequestBody Article article){
		Letter<Map<String,Object>> letter = new Letter<Map<String,Object>>();
		try {
			List<Map<String,Object>> list = articleService.getReadNum(article);
			letter.setList(list);
			letter.setDetail("数据获取成功");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据获取失败！");
		}
		return letter;
	}


	@Jurisdiction(value = "getPageAuthor")
	@RequestMapping(value = "/getPageAuthor",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<Article> getPageAuthor(@RequestBody JSONObject object) {
		Letter<Article> letter = new Letter<Article>();
		try{
			letter = this.getPage(object);
			if(letter.getResult().equals("SUCCESS")){
				letter.getList().forEach(e->{
					ArticleState articleState = new ArticleState();
					articleState.setArticleId(e.getId());
					List<ArticleState> list = articleStateService.selectList(articleState);
					e.setAudits(list);
				});
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return letter;
	}

	@Jurisdiction(value = "getArticleById")
	@RequestMapping(value = "/getArticleById",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<Article> getArticleById(@RequestBody Article article) {
		Letter<Article> letter = new Letter<Article>();
		try{
			article = articleService.getArticleById(article);
			if(article!=null){
				letter.setDetail("数据获取成功");
				letter.setResult("SUCCESS");
				letter.setData(article);
			}else{
				letter.setDetail("数据异常");
				letter.setResult("FAIL");
			}
		}catch (Exception e){
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据获取失败！");
		}
		return letter;
	}


	/**
	 * app 书城界面获取数据
	 * 1.排行榜数据
	 * 2.精选数据
	 * 3.最新数据
	 * {
	 *     viewType - 视图类型
	 *     pic - 图片url
	 *     articleName - 文章名称
	 *     introduction - 文章介绍
	 *     articleType - 文章类型
	 *     articleType - 阅读数量
	 *     authorName - 作者名称
	 *     authorId - 作者id
	 *     id - 文章ID
	 * }
	 * @return
	 */
	@Jurisdiction(value = "getData")
	@RequestMapping(value = "/getData",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<JSONObject> getData(HttpServletRequest request){
		Letter<JSONObject> letter = new Letter<>();
		try{
			List<JSONObject> jsonObject = new ArrayList<>();
			List<JSONObject> articles ;
			// 获取排行榜
			articles = articleService.getLeaderboard();
			if(!DataTool.isBlank(articles)){
				jsonObject.addAll(articles);
			}
			// 获取精选信息
			String userId = DataTool.getUserIdFromSession(request);
			if(userId != null){
				articles = articleService.getFeatured(1,userId);
				if(!DataTool.isBlank(articles)){
					jsonObject.addAll(articles);
				}
			}
			// 获取最新文章信息
			articles = articleService.getArticle(1);
			if(!DataTool.isBlank(articles)){
				jsonObject.addAll(articles);
			}
			letter.setResult("SUCCESS");
			letter.setDetail("数据获取成功");
			letter.setList(jsonObject);
		}catch (Exception e){
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail(e.getLocalizedMessage());
		}
		return letter;
	}

	@Jurisdiction(value = "getArticleByType")
	@RequestMapping(value = "/getArticleByType",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<Article> getArticleByType(@RequestBody JSONObject object){
		Letter<Article> letter = new Letter<Article>();
		try {
			List<Article> result = articleService.getArticleByType(object);
			result.forEach(e->{
				ArticleTypeRel rel = new ArticleTypeRel();
				rel.setArticleId(e.getId());
				List<ArticleTypeRel> rels = articleTypeRelService.selectList(rel);
				List<String> ids = new ArrayList<>();
				rels.forEach(r->{
					ids.add(r.getTypeId());
				});
				List<ArticleType> articleTypes = articleTypeService.selectByIds(ids);
				e.setArticleTypes(articleTypes);
			});
			letter.setList(result);
			letter.setDetail("数据获取成功");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据获取失败！");
		}
		return letter;
	}

	/**
	 * 根据作者ID获取作品信息
	 * @param object
	 * @return
	 */
	@Jurisdiction(value = "getArticleByAuthor")
	@RequestMapping(value = "/getArticleByAuthor",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<Article> getArticleByAuthor(@RequestBody JSONObject object){
		Letter<Article> letter = new Letter<Article>();
		try {
			String authorId = object.getString("authorId");
			if(DataTool.isBlank(authorId)){
				letter.setDetail("数据异常");
				letter.setResult("FAIL");
				return letter;
			}
			List<Article> result = articleService.getArticleByAuthor(authorId);
			result.forEach(e->{
				ArticleTypeRel rel = new ArticleTypeRel();
				rel.setArticleId(e.getId());
				List<ArticleTypeRel> rels = articleTypeRelService.selectList(rel);
				List<String> ids = new ArrayList<>();
				rels.forEach(r->{
					ids.add(r.getTypeId());
				});
				List<ArticleType> articleTypes = articleTypeService.selectByIds(ids);
				e.setArticleTypes(articleTypes);
			});
			letter.setList(result);
			letter.setDetail("数据获取成功");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据获取失败！");
		}
		return letter;
	}


	/**
	 * 根据文章ID获取文件并转化为字符串
	 * @param article
	 * @return
	 */
	@Jurisdiction(value = "getContent")
	@RequestMapping(value = "/getContent",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<String> getContent(@RequestBody Article article){
		Letter<String> letter = new Letter<String>();
		try {
			String articleId = article.getId();
			String text = articleService.getContent(articleId);
			if(DataTool.isBlank(text)){
				letter.setResult("FAIL");
				letter.setDetail("数据获取失败");
			}else{
				letter.setData(text);
				letter.setDetail("数据获取成功");
				letter.setResult("SUCCESS");
			}
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据获取失败！");
		}
		return letter;
	}



     /**
	 * 根绝条件获取数据
	 * @return
	 */
    @Jurisdiction(value = "selectList")
	@RequestMapping(value = "/selectList",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<Article> selectList(@RequestBody Article article){
		Letter<Article> letter = new Letter<Article>();
		try {

			List<Article> result = articleService.selectList(article);
			letter.setList(result);
			letter.setDetail("数据获取成功");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据获取失败！");
		}
		return letter;
	}

	/**
	 * 根据条件获取一个
	 * @param article
	 * @return
	 */
	@Jurisdiction(value = "selectOne")
	@RequestMapping(value = "/selectOne",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<Article> selectOne(@RequestBody Article article){
		Letter<Article> letter = new Letter<Article>();
		try {
			Article obj = articleService.selectOne(article);
			letter.setData(obj);
			letter.setDetail("数据获取成功！");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据获取失败！");
		}
		return letter;
	}

	/**
	 * 插入数据
	 * @param article
	 * @return
	 */
	@Jurisdiction(value = "insert")
	@RequestMapping(value = "/insert",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<String> insert(@RequestBody Article article){
		Letter<String> letter = new Letter<String>();
		article.setId(DataTool.createUUID());
		article.setState("0");
		Map<String , String> sub = SubjectNotNull.subject(article);
		if(sub.size() != 0) {
			letter.setResult("FAIL");
			letter.setDetail("必填信息不能为空！" + sub.toString());
			return letter;
		}
		try {
			articleService.insertArticle(article,letter);
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据插入失败！");
		}
		return letter;
	}

	/**
	 * 修改
	 * @param article
	 * @return
	 */
	@Jurisdiction(value = "alter")
	@RequestMapping(value = "/alter",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<String> alter(@RequestBody Article article){
		Letter<String> letter = new Letter<String>();
		try {
			articleService.alter(article,letter);
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据插入失败！");
		}
		return letter;
	}

	/**
	 * 批量插入数据
	 * @param articles
	 * @return
	 */
	@Jurisdiction(value = "insertBatch")
	@RequestMapping(value = "/insertBatch",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<String> insertBatch(@RequestBody List<Article> articles){
		Letter<String> letter = new Letter<String>();
		try {
			articleService.insertBatch(articles,letter);
			letter.setResult("SUCCESS");
			letter.setDetail("数据插入成功！");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据插入失败！");
		}
		return letter;
	}

	/**
	 * 根绝条件进行删除
	 * @param article
	 * @return
	 */
	@Jurisdiction(value = "delete")
	@RequestMapping(value = "/delete",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<String> delete(@RequestBody Article article){
		Letter<String> letter = new Letter<String>();
		if(SubjectNotNull.subjectIsNull(article)) {
			letter.setResult("FAIL");
			letter.setDetail("信息不能为空！");
			return letter;
		}
		try {
			articleService.delete(article);
			letter.setDetail("数据删除成功");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据删除失败！");
		}
		return letter;
	}
    /**
    * 根据id批量删除
    */
    @Jurisdiction(value = "deletes")
    @RequestMapping(value = "/deletes",produces = MediaType.APPLICATION_JSON_VALUE)
    public Letter<String> deletes(@RequestBody List<Article> articles){
        Letter<String> letter = new Letter<String>();
        if(DataTool.isBlank(articles)) {
            letter.setResult("FAIL");
            letter.setDetail("信息不能为空！");
            return letter;
        }
        try {
			articleService.deletes(articles);
            letter.setDetail("数据删除成功");
            letter.setResult("SUCCESS");
        }catch (Exception e) {
            e.printStackTrace();
            letter.setResult("ERROR");
            letter.setDetail("数据删除失败！");
        }
        return letter;
    }

	/**
	 * 根绝id更新
	 * @param article
	 * @return
	 */
	@Jurisdiction(value = "updateById")
	@RequestMapping(value = "/updateById",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<String> updateById(@RequestBody Article article){
		Letter<String> letter = new Letter<String>();
		if(article.getId().equals("")) {
			letter.setResult("FAIL");
			letter.setDetail("id不能为空！");
			return letter;
		}
		try {
			articleService.updateById(article);
			letter.setDetail("数据修改成功");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据修改失败！");
		}
		return letter;
	}
}
